<template>
  <q-page class="q-pa-md">
    <!-- 查询表单 -->
    <q-card flat bordered class="q-mb-md">
      <q-card-section>
        <div class="text-h6">白名单查询</div>
      </q-card-section>
      <q-card-section>
        <q-form @submit="handleSearch" class="row q-col-gutter-md">
          <q-input
            v-model="searchForm.ipAddress"
            label="IP地址"
            outlined
            dense
            clearable
            class="col-md-4 col-sm-6 col-xs-12"
          />
          <q-input
            v-model="searchForm.description"
            label="描述"
            outlined
            dense
            clearable
            class="col-md-4 col-sm-6 col-xs-12"
          />
          <q-select
            v-model="searchForm.status"
            label="状态"
            :options="statusOptions"
            outlined
            dense
            emit-value
            map-options
            class="col-md-4 col-sm-6 col-xs-12"
          />
          <div class="col-md-12 flex justify-end">
            <q-btn type="submit" color="primary" label="查询" class="q-mr-sm" />
            <q-btn @click="resetSearch" label="重置" outline color="primary" />
          </div>
        </q-form>
      </q-card-section>
    </q-card>

    <!-- 操作按钮和表格 -->
    <q-card flat bordered>
      <q-card-section class="row items-center">
        <div class="text-h6 col">白名单列表</div>
        <div class="col-auto q-gutter-sm">
          <q-btn color="primary" label="新增白名单" icon="add" @click="showAddDialog" />
          <q-btn
            color="negative"
            label="批量删除"
            icon="delete"
            :disable="selected.length === 0"
            @click="confirmBatchDelete"
          />
          <q-btn color="secondary" label="刷新缓存" icon="cached" @click="refreshCache" />
        </div>
      </q-card-section>

      <!-- 数据表格 -->
      <q-table
        v-model:selected="selected"
        :rows="whitelist"
        :columns="columns"
        row-key="id"
        :loading="loading"
        :pagination="pagination"
        @request="onRequest"
        selection="multiple"
        binary-state-sort
        flat
        bordered
      >
        <!-- 状态列 -->
        <template v-slot:body-cell-status="props">
          <q-td :props="props">
            <q-toggle
              v-model="props.row.status"
              checked-icon="check"
              unchecked-icon="clear"
              :true-value="1"
              :false-value="0"
              color="green"
              @update:model-value="toggleStatus(props.row)"
            />
          </q-td>
        </template>

        <!-- 操作列 -->
        <template v-slot:body-cell-actions="props">
          <q-td :props="props" class="q-gutter-x-sm">
            <q-btn dense color="primary" icon="edit" @click="showEditDialog(props.row)">
              <q-tooltip>编辑</q-tooltip>
            </q-btn>
            <q-btn dense color="negative" icon="delete" @click="confirmDelete(props.row.id)">
              <q-tooltip>删除</q-tooltip>
            </q-btn>
          </q-td>
        </template>
      </q-table>
    </q-card>

    <!-- 新增/编辑对话框 -->
    <q-dialog v-model="dialogVisible" persistent>
      <q-card style="min-width: 500px">
        <q-card-section>
          <div class="text-h6">{{ isEdit ? '编辑白名单' : '新增白名单' }}</div>
        </q-card-section>

        <q-card-section class="q-pt-none">
          <q-form @submit="submitForm" class="q-gutter-md">
            <q-input
              v-model="whitelistForm.ipAddress"
              label="IP地址"
              :rules="[
                (val) => !!val || 'IP地址不能为空',
                (val) => isValidIP(val) || '请输入有效的IP地址',
              ]"
              outlined
            />

            <q-input
              v-model="whitelistForm.description"
              label="描述"
              :rules="[(val) => !!val || '描述不能为空']"
              outlined
            />

            <q-select
              v-model="whitelistForm.status"
              label="状态"
              :options="statusOptions.filter((s) => s.value !== '')"
              outlined
              emit-value
              map-options
            />

            <div class="flex justify-end q-gutter-sm">
              <q-btn label="取消" v-close-popup flat color="primary" />
              <q-btn type="submit" :label="isEdit ? '保存' : '创建'" color="primary" />
            </div>
          </q-form>
        </q-card-section>
      </q-card>
    </q-dialog>
  </q-page>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useQuasar } from 'quasar'

const $q = useQuasar()

// 表格列定义
const columns = [
  { name: 'select', label: '选择', field: '', align: 'center' },
  { name: 'ipAddress', label: 'IP地址', field: 'ipAddress', align: 'center', sortable: true },
  { name: 'description', label: '描述', field: 'description', align: 'center' },
  { name: 'status', label: '状态', field: 'status', align: 'center' },
  { name: 'createTime', label: '创建时间', field: 'createTime', align: 'center', sortable: true },
  { name: 'updateTime', label: '更新时间', field: 'updateTime', align: 'center', sortable: true },
  { name: 'actions', label: '操作', align: 'center' },
]

// 状态选项
const statusOptions = [
  { label: '全部', value: '' },
  { label: '启用', value: '1' },
  { label: '禁用', value: '0' },
]

// 数据状态
const whitelist = ref([])
const selected = ref([])
const loading = ref(false)
const pagination = ref({
  page: 1,
  rowsPerPage: 10,
  rowsNumber: 0,
})
const searchForm = ref({
  ipAddress: '',
  description: '',
  status: '',
})
const dialogVisible = ref(false)
const isEdit = ref(false)
const whitelistForm = ref({
  id: null,
  ipAddress: '',
  description: '',
  status: '1',
})

// 初始化加载数据
onMounted(() => {
  loadWhitelist()
})

// 加载白名单数据
function loadWhitelist(props) {
  if (!props) {
    props = { pagination: pagination.value }
  }

  loading.value = true
  const { page, rowsPerPage } = props.pagination

  // 模拟API请求
  setTimeout(() => {
    // 这里应该是实际的API调用
    // 模拟数据
    const mockData = Array.from({ length: rowsPerPage }, (_, i) => ({
      id: (page - 1) * rowsPerPage + i + 1,
      ipAddress: `192.168.1.${i + 1}`,
      description: ['内部服务器', '管理员IP', '合作伙伴', 'VPN接入', '测试环境'][i % 5],
      status: Math.random() > 0.3 ? 1 : 0,
      createTime: new Date(Date.now() - i * 24 * 3600 * 1000).toISOString(),
      updateTime: new Date(Date.now() - i * 12 * 3600 * 1000).toISOString(),
    }))

    // 应用查询条件
    let filteredData = [...mockData]
    if (props.filter.ipAddress) {
      filteredData = filteredData.filter((item) => item.ipAddress.includes(props.filter.ipAddress))
    }
    if (props.filter.description) {
      filteredData = filteredData.filter((item) =>
        item.description.includes(props.filter.description),
      )
    }
    if (props.filter.status) {
      filteredData = filteredData.filter((item) => item.status.toString() === props.filter.status)
    }

    whitelist.value = filteredData
    pagination.value.rowsNumber = filteredData.length
    pagination.value.page = page
    pagination.value.rowsPerPage = rowsPerPage
    loading.value = false
  }, 500)
}

// 表格请求方法
function onRequest(props) {
  loadWhitelist(props)
}

// 查询处理
function handleSearch() {
  pagination.value.page = 1
  onRequest({
    pagination: pagination.value,
    filter: searchForm.value,
  })
}

// 重置查询
function resetSearch() {
  searchForm.value = {
    ipAddress: '',
    description: '',
    status: '',
  }
  handleSearch()
}

// 验证IP地址格式
function isValidIP(ip) {
  const ipv4Regex =
    /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/
  const ipv6Regex = /^([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$/
  return ipv4Regex.test(ip) || ipv6Regex.test(ip)
}

// 显示新增对话框
function showAddDialog() {
  isEdit.value = false
  whitelistForm.value = {
    id: null,
    ipAddress: '',
    description: '',
    status: '1',
  }
  dialogVisible.value = true
}

// 显示编辑对话框
function showEditDialog(row) {
  isEdit.value = true
  whitelistForm.value = {
    ...row,
    status: row.status.toString(),
  }
  dialogVisible.value = true
}

// 提交表单
function submitForm() {
  // 这里应该是实际的API调用
  $q.notify({
    type: 'positive',
    message: isEdit.value ? '白名单已更新' : '白名单创建成功',
  })
  dialogVisible.value = false
  loadWhitelist()
}

// 切换状态
function toggleStatus(row) {
  $q.dialog({
    title: '确认',
    message: `确定要${row.status === 0 ? '启用' : '禁用'}IP "${row.ipAddress}"  吗？`,
    cancel: true,
  })
    .onOk(() => {
      // 这里应该是实际的API调用
      $q.notify({
        type: 'positive',
        message: `IP ${row.ipAddress}  已${row.status === 0 ? '启用' : '禁用'}`,
      })
    })
    .onCancel(() => {
      // 取消操作时恢复原来的状态
      row.status = row.status === 0 ? 1 : 0
    })
}

// 确认删除
function confirmDelete(id) {
  $q.dialog({
    title: '确认删除',
    message: '确定要删除该白名单吗？此操作不可恢复！',
    cancel: true,
    persistent: true,
  }).onOk(() => {
    // 这里应该是实际的API调用
    $q.notify({
      type: 'positive',
      message: '白名单已删除',
    })
    loadWhitelist()
  })
}

// 批量删除
function confirmBatchDelete() {
  if (selected.value.length === 0) return

  $q.dialog({
    title: '确认批量删除',
    message: `确定要删除选中的 ${selected.value.length}  个白名单吗？此操作不可恢复！`,
    cancel: true,
    persistent: true,
  }).onOk(() => {
    // 这里应该是实际的API调用
    $q.notify({
      type: 'positive',
      message: '已删除选中的白名单',
    })
    selected.value = []
    loadWhitelist()
  })
}

// 刷新缓存
function refreshCache() {
  loading.value = true
  // 模拟API请求
  setTimeout(() => {
    $q.notify({
      type: 'positive',
      message: '白名单缓存已刷新',
    })
    loading.value = false
  }, 1000)
}
</script>

<style lang="scss" scoped>
.q-table {
  thead tr th {
    font-weight: bold;
    background-color: #f5f5f5;
  }

  tbody tr:hover {
    background-color: #f5f5f5;
  }
}
</style>
